package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报表
 */

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        Map data = new HashMap();
        List<String> months = new ArrayList();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,-12);//2018-12-10
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);//2019-1-10
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        data.put("months",months);

        List<Integer> memberCount = memberService.findMemberCountByMonths(months);

        data.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,data);
    }

    //查询套餐预约占比数据统计
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        /*Map map = new HashMap();
        List<String> setmealNames = new ArrayList<>();
        setmealNames.add("直接访问");
        setmealNames.add("邮件营销");
        map.put("setmealNames",setmealNames);

        List<Map<String,Object>> setmealCount = new ArrayList();
        Map map1 = new HashMap();
        map1.put("name","直接访问");
        map1.put("value",100);

        Map map2 = new HashMap();
        map2.put("name","邮件营销");
        map2.put("value",200);

        setmealCount.add(map1);
        setmealCount.add(map2);
        map.put("setmealCount",setmealCount);

        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);*/


        List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();

        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> map : setmealCount) {
            String name = (String) map.get("name");
            setmealNames.add(name);
        }

        Map map = new HashMap();
        map.put("setmealNames",setmealNames);
        map.put("setmealCount",setmealCount);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
    }

    @Reference
    private ReportService reportService;

    //获取运营数据统计
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        Map<String,Object> map = null;
        try {
            map = reportService.getBusinessReport();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
    }

    //运营数据报表导出
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> result = null;
        try {
            //调用Service获取运营数据
            result = reportService.getBusinessReport();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //使用POI将查询到的数据写入到Excel文件中
            String templateDirPath = request.getSession().getServletContext().getRealPath("template");
            String filePath = templateDirPath + File.separator + "report_template.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //获取第一个Sheet工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int num = 12;
            //热门套餐
            for (Map map : hotSetmeal) {
                row = sheet.getRow(num ++);
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            //通过输出流将Excel文件下载到客户端
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
    @RequestMapping("getreportdate")
    public Result getreportdate(@RequestBody HashMap<String, Object> map) {
        System.out.println(map);
        String value1 =  map.get("value1").toString();
        String value2 =  map.get("value2").toString();
        try {
            Date date1 = DateUtils.parseString2Date(value1);
            Date date2 = DateUtils.parseString2Date(value2);
            String date1String = DateUtils.parseDate2String(date1, "yyyy-MM-dd");
            String date2String = DateUtils.parseDate2String(date2, "yyyy-MM-dd");

            System.out.println(date1String);
            System.out.println(date2String);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(sdf.parse(date1String));
            c2.setTime(sdf.parse(date2String));

            int month = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
            int year = c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR);
            if (year > 0) {
                month = year * 12 + month + 1;
            } else {
                month = month + 1;
            }
            Map data = new HashMap();
            List<String> months = new ArrayList();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            for (int i = 0; i < month; i++) {
                calendar.add(Calendar.MONTH, 1);
                months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }
            data.put("months", months);

            List<Integer> memberCount = memberService.findMemberCountByMonths(months);

            data.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, data);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
    }
    @RequestMapping("/getMemberAgeReport")
    public Result getMemberAgeReport(){
        try {
            List<Map<String,Object>> list = memberService.findMemberAgeCount();
            Map<String,Object> map = new HashMap<>();
            map.put("ageCount",list);

            List<String> memberAge = new ArrayList<>();

            for (Map<String, Object> maplist : list) {
                String name = (String) maplist.get("name");
                memberAge.add(name);

            }

            map.put("memberAge",memberAge);
            return new Result(true,MessageConstant.GET_MEMBERAGE_COUNT_REPORT_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBERAGE_COUNT_REPORT_FAIL);
        }
    }
    @RequestMapping("/getMemberSexReport")
    public Result getMemberSexReport(){
        try {
            List<Map<String,Object>> list =  memberService.findMemberSexCount();
            Map<String,Object> map = new HashMap<>();
            map.put("sexCount",list);
            List<String> memberSex = new ArrayList<>();
            for (Map<String,Object> maplist : list){
                String name = (String) maplist.get("name");
                memberSex.add(name);
            }
            map.put("memberSex",memberSex);
            return new Result(true,MessageConstant.GET_MEMBERSEX_COUNT_REPORT_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBERSEX_COUNT_REPORT_FAIL);
        }
    }

}
